import CodeTable from '@/services/data-factory/index';
import type { ProColumns } from '@ant-design/pro-components';
import { EditableProTable, ProFormRadio } from '@ant-design/pro-components';
import { Button, Form, Input, message, Modal, Space } from 'antd';
import React, { PropsWithChildren, useEffect, useState } from 'react';
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const {
  addCodeTableUsingPost,
  getCodeTableDetailUsingGet,
  updateCodeTableUsingPost,
} = CodeTable.codeTableguanlikongzhiqi;
type FieldType = {
  codeTableName: string;
  codeTableDescription?: string;
  // DataSourceType: DataSourceType[];
  codeTableSetting: DataSourceType[];
};
type DataSourceType = {
  codeValue: string;
  codeName: string;
  codeMean: string;
  // codeTableSetting?: DataSourceType[];
  id: number;
};
interface CreateFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSuccess: () => void; // 增加成功回调
  getCodeTableList: () => void; // 增加成功回调
  initialValues?: FieldType; // 添加 initialValues 属性
}
// const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
//   console.log('Success:', values);
// };

// const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
//   console.log('Failed:', errorInfo);
// };

// const defaultData: DataSourceType[] = [];
const CreateForm: React.FC<
  PropsWithChildren<CreateFormProps & { codeTableId?: string }>
> = (props) => {
  const { modalVisible, onCancel, codeTableId, initialValues } = props;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>(
    'bottom',
  );

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '编码取值',
      dataIndex: 'codeValue',
      // tooltip: '只读，使用form.getFieldValue获取不到值',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
      width: '15%',
    },
    {
      title: '编码名称',
      dataIndex: 'codeName',

      width: '15%',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
    },
    {
      title: '码值含义',
      dataIndex: 'codeMean',
      width: '15%',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const [form] = Form.useForm();
  useEffect(() => {
    if (codeTableId === undefined) {
      form.resetFields();
      setDataSource([]);
      return;
    }
    if (initialValues) {
      form.setFieldsValue({
        codeTableName: initialValues.codeTableName,
        codeTableDescription: initialValues.codeTableDescription,
        codeTableSetting: initialValues.codeTableSetting
          ? initialValues.codeTableSetting.map((item) => ({
              id: item.id,
              codeValue: item.codeValue,
              codeName: item.codeName,
              codeMean: item.codeMean,
            }))
          : [],
      });
      setDataSource(
        initialValues.codeTableSetting
          ? initialValues.codeTableSetting.map((item) => ({
              id: item.id,
              codeValue: item.codeValue,
              codeName: item.codeName,
              codeMean: item.codeMean,
            }))
          : [],
      );
    } else {
      form.resetFields();
      setDataSource([]);
    }
  }, [initialValues, codeTableId]);

  // 码表详情
  const getCodeTableDetail = async () => {
    if (codeTableId) {
      const res = await getCodeTableDetailUsingGet({ codeTableId });
      // 回填可编辑表格数据
      console.log('详情：', res.data);

      setDataSource(res.data.codeTableSetting);
    }
  };
  //
  useEffect(() => {
    console.log('codeTableId', codeTableId);
    getCodeTableDetail();
  }, [codeTableId]);
  // 重置
  const onReset = () => {
    form.resetFields();
  };
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const onSuccess = () => {
    console.log(createModalVisible);
    handleModalVisible(false);
  };
  // 新增  编辑
  const handleAdd = async (form: any) => {
    // debugger;
    try {
      if (codeTableId) {
        // debugger;
        const values = form.getFieldsValue();
        const res = await updateCodeTableUsingPost({
          codeTableId: codeTableId,
          codeTableName: values.codeTableName,
          codeTableDescription: values.codeTableDescription,
          codeTableSetting: values.DataSourceType.map((item: any) => ({
            codeValue: item.codeValue,
            codeName: item.codeName,
            codeMean: item.codeMean,
          })),
        });
        console.log(res);
        message.success('编辑成功');
        onCancel(); // 关闭弹窗
        onSuccess();
        form.resetFields();

        props.getCodeTableList(); // 调用父组件的获取列表函数
      } else {
        const values = form.getFieldsValue();
        const res = await addCodeTableUsingPost({
          codeTableName: values.codeTableName,
          codeTableDescription: values.codeTableDescription,
          codeTableSetting: values.DataSourceType.map((item: any) => ({
            codeValue: item.codeValue,
            codeName: item.codeName,
            codeMean: item.codeMean,
          })),
        });
        message.success('新增成功');
        onCancel(); // 关闭弹窗
        onSuccess();
        form.resetFields();

        await console.log('请求成功', res);
        // getCodeTableDetail();
        props.getCodeTableList(); // 调用父组件的获取列表函数
      }
    } catch (error) {
      console.log('请求失败:', error);
    }
  };

  //
  return (
    <Modal
      destroyOnClose
      title={`${codeTableId ? '编辑' : '新增'}码表`}
      width={800}
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
      style={{ backgroundColor: 'gray', borderColor: 'red' }}
    >
      {/* {props.children} */}
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        // onFinish={onFinish}
        // onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="码表名称"
          name="codeTableName"
          rules={[{ required: true, message: '请输入码表名称!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType> label="码表说明" name="codeTableDescription">
          <Input />
        </Form.Item>
        <Form.Item<FieldType>
          label="编码配置"
          name="DataSourceType"
          rules={[{ required: true, message: '请输入编码配置!' }]}
        >
          <br />
          <EditableProTable<DataSourceType>
            rowKey="id"
            maxLength={5}
            style={{ width: 600, marginLeft: -100, minHeight: 300 }}
            scroll={{
              x: 960,
            }}
            recordCreatorProps={
              position !== 'hidden'
                ? {
                    position: position as 'top',
                    record: () => ({
                      id: (Math.random() * 1000000).toFixed(0),
                    }),
                  }
                : false
            }
            loading={false}
            toolBarRender={() => [
              <ProFormRadio.Group
                key="render"
                fieldProps={{
                  value: position,
                  onChange: (e) => setPosition(e.target.value),
                }}
                options={[
                  {
                    label: '添加到底部',
                    value: 'bottom',
                  },
                ]}
              />,
            ]}
            columns={columns}
            request={async () => ({
              data: dataSource,
              total: dataSource.length,
              success: true,
            })}
            value={dataSource}
            // onChange={setDataSource}
            onChange={(dataSource) => {
              setDataSource(dataSource);
              form.setFieldsValue({ DataSourceType: dataSource });
            }}
            editable={{
              type: 'multiple',
              editableKeys,
              onSave: async (rowKey, data, row) => {
                console.log(rowKey, data, row);
                await waitTime(1000);
              },
              onChange: setEditableRowKeys,
            }}
          />
        </Form.Item>
        <Form.Item label={null} wrapperCol={{ span: 24, offset: 12 }}>
          <Space>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
            <Button type="primary" onClick={() => handleAdd(form)}>
              确认
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateForm;
